<template>
	<view class="order-pages" :style="{background:pageColor}" v-if="isLoad">
		<view class="space-md"></view>
		<view v-if="orderInfo.order_goods && orderInfo.order_goods.length > 0">
			<view class="ml-lg mr-lg  fill-base radius-16">
				<view class="list-item flex-center pd-lg" :class="[{'b-1px-t':index!=0}]"
					v-for="(item,index) in orderInfo.order_goods" :key="index">
					<!-- #ifdef H5 -->
					<view class="item-img radius-16">
						<view class="h5-image item-img radius-16" :style="{ backgroundImage : `url('${item.cover}')`}">
						</view>
					</view>
					<!-- #endif -->
					<!-- #ifndef H5 -->
					<image mode="aspectFill" class="item-img radius-16" :src="item.cover"></image>
					<!-- #endif -->
					<!-- order_type 1升级；2加时 -->
					<view class="flex-1 ml-md">
						<view :class="[{'flex-between':bellOrderParams.order_type==1}]">
							<view class="f-title c-title text-bold ellipsis"
								:class="[{'max-400':bellOrderParams.order_type==1},{'max-470':bellOrderParams.order_type==2}]">
								{{item.title}}
							</view>
							<view class="f-caption c-caption" v-if="bellOrderParams.order_type==1">x{{item.num}}
							</view>
						</view>
						<view class="flex-center mt-sm">
							<view class="flex-1 flex-y-center f-desc c-caption">
								<view class="f-title c-warning mr-sm">
									¥{{bellOrderParams.order_type==1?item.pay_price:item.price}}</view>
								{{`/ ${item.time_long}`}}分钟
							</view>
							<view class="member-canbuy-level" v-if="item.member_info && item.member_info.title">
								<view class="text flex-center">{{item.member_info.title}}专享</view>
							</view>
						</view>
						<view class="flex-between mt-sm">
							<view class="f-caption c-caption ellipsis" style="max-width: 300rpx;">
								{{$t('action.attendantName').substring(0, 2) === '服务' ? '' : '服务'}}{{$t('action.attendantName')}}：{{orderInfo.coach_info?orderInfo.coach_info.coach_name:'-'}}
							</view>
							<view>
								<view class="flex-warp" v-if="bellOrderParams.order_type==2">
									<button @tap.stop="changeNum(-1,index)" class="reduce"
										:style="{borderColor:primaryColor,color:primaryColor}"><i
											class="iconfont icon-jian-bold"></i></button>
									<button class="addreduce clear-btn">{{item.num || 0}}</button>
									</block>
									<button @tap.stop="changeNum(1,index)" class="add"
										:style="{background:primaryColor,borderColor:primaryColor}"><i
											class="iconfont icon-jia-bold"></i></button>
								</view>
							</view>
						</view>
					</view>
				</view>
			</view>
			<view class="mt-md ml-lg mr-lg fill-base radius-16">
				<view class="flex-between pd-lg b-1px-b">
					<view class="f-title c-title text-bold">服务开始时间</view>
					<view class="f-paragraph text-bold" :style="{color:primaryColor}">
						{{orderInfo.order_start_time}}
					</view>
				</view>
				<view class="flex-between pd-lg">
					<view class="f-title c-title text-bold">服务结束时间</view>
					<view class="f-paragraph text-bold" :style="{color:primaryColor}">
						{{orderInfo.order_end_time}}
					</view>
				</view>
			</view>

			<view class="mt-md ml-lg mr-lg fill-base radius-16" v-if="orderInfo.del_coupon_discount*1>0">
				<view class="flex-between pd-lg">
					<view class="f-title c-title text-bold">卡券优惠</view>
					<view class="f-paragraph c-warning mr-sm">
						{{`-¥${orderInfo.del_coupon_discount}`}}
					</view>
				</view>
			</view>

			<view class="mt-md ml-lg mr-lg fill-base radius-16"
				v-if="orderInfo.member_status || (bellOrderParams.order_type == 1 && (orderInfo.member_discount_balance*1>0 || orderInfo.member_discount_cash*1>0))">
				<view @tap.stop="toUseDiscountCard" class="flex-between pd-lg">
					<view class="f-title c-title text-bold">会员折扣</view>
					<view class="flex-y-center f-paragraph c-caption">
						<view
							:class="[{'c-warning':orderInfo.member_discount_balance*1>0 || orderInfo.member_discount_cash*1>0}]"
							v-if="orderInfo.is_remember || bellOrderParams.order_type == 1">
							{{(orderInfo.member_discount_balance*1>0 || orderInfo.member_discount_cash*1>0)  ? `${orderInfo.member_discount_balance}折 (优惠¥${orderInfo.member_discount_cash})` : '-'}}
						</view>
						<view class="flex-y-center" v-if="bellOrderParams.order_type != 1 && !orderInfo.is_remember">
							<span class="flex-center f-icontext c-base mr-sm"
								style="min-width:30rpx;height:34rpx;padding:0 12rpx; background: #F13F26;border-radius: 8rpx;">待使用</span>点击使用会员优惠
						</view>
					</view>
				</view>
			</view>

			<view class="mt-md ml-lg mr-lg fill-base radius-16">
				<view @tap.stop="toChangeItem(index,2)" class="flex-warp pt-lg pb-lg ml-lg mr-lg f-title c-title"
					:class="[{'b-1px-t':index!=0 && bellOrderParams.order_type!=1}]" v-for="(item,index) in payList"
					:key="index"
					v-show="(bellOrderParams.order_type==1 && item.id == orderInfo.pay_model) || bellOrderParams.order_type!=1">
					<i class="iconfont mr-md" :class="item.icon" style="font-size: 50rpx;"></i>
					<view class="flex-1">
						<view class="flex-between">
							<view class="flex-y-center">
								<view>{{item.title}}</view>
								<view class="f-paragraph c-caption ml-md" v-if="item.id == 2">
									余额{{orderInfo.user_cash || 0}}元
								</view>
								<view class="flex-center f-icontext ml-md"
									style="padding:5rpx 10rpx;color:#FF2D00;background:#FDF5F0;border-radius: 2rpx;"
									v-if="item.id == 4 && orderInfo.balance_discount_data && ((bellOrderParams.order_type==1&&!orderInfo.balance_discount_data.is_balancediscount) || (bellOrderParams.order_type==2&&(orderInfo.balance_discount_data.is_balancediscount==0 || orderInfo.balance_discount_data.user_status==0)))">
									当前无可用卡/卡余额不足</view>
							</view>
							<view @tap.stop="$util.goUrl({url:`/user/pages/stored/card-use`})"
								class="flex-y-center f-desc" style="#6A6A6A"
								v-if="item.id==4&&orderInfo.balance_discount_data&&orderInfo.balance_discount_data.is_balancediscount">
								重选<i class="iconfont icon-right text-bold"
									style="font-size: 20rpx;margin-left: 5rpx;"></i>
							</view>
							<i class="pay-icon iconfont icon-xuanze mr-sm"
								:class="[{'icon-radio-fill': payInd == index}]"
								:style="{color:payInd == index ? primaryColor:'#999'}" v-else></i>
						</view>
						<view class="mt-sm f-desc" :style="{color:primaryColor}"
							v-if="item.id==4 && orderInfo.balance_discount_data">
							<view @tap.stop="$util.goUrl({url:`/user/pages/stored/list`})" class="flex-between"
								v-if="orderInfo.balance_discount_data && ((bellOrderParams.order_type==1&&!orderInfo.balance_discount_data.is_balancediscount) || (bellOrderParams.order_type==2&&(orderInfo.balance_discount_data.is_balancediscount==0 || orderInfo.balance_discount_data.user_status==0)))">
								<view>最高可享受{{ orderInfo.balance_discount_data.min_discount}}折优惠</view>
								<view class="flex-y-center">+添加新卡<i class="iconfont icon-right text-bold"
										style="font-size: 22rpx;"></i></view>
							</view>
							<block v-if="orderInfo.balance_discount_data.balance_discount_list">
								<view v-for="(aitem,aindex) in orderInfo.balance_discount_data.balance_discount_list"
									:key="aindex">
									{{aitem.title}} (消费{{aitem.value_cash}}元)
								</view>
							</block>
						</view>
					</view>
				</view>
			</view>

			<view class="space-max-footer"></view>

			<view class="pay-info fix flex-between text-right pl-lg pr-lg fill-base">
				<view class="flex-y-center f-paragraph c-title text-bold ml-sm mr-lg">合计：
					<view class="flex-y-baseline f-title c-warning">¥{{orderInfo.pay_price}}</view>
				</view>
				<auth :needAuth="!userInfo || (userInfo && (!userInfo.phone || !userInfo.nickName))"
					:type="!userInfo.phone ? 'phone' : 'userInfo'" @go="toPay" style="width: 182rpx;">
					<view class="pay-btn flex-center f-paragraph c-base radius" :style="{background:primaryColor}">
						立即支付</view>
				</auth>
			</view>

		</view>

		<abnor @confirm="$util.goUrl({url:1,openType:`navigateBack`})" :tip="[{ text: '该服务已下架~', color: 0 }]"
			:button="[{ text: '去看看其他加时服务' , type: 'confirm' }]" btnSize="" v-else>
		</abnor>

	</view>
</template>

<script>
	import {
		mapState,
		mapActions,
		mapMutations
	} from "vuex"
	import parser from "@/components/jyf-Parser/index"
	export default {
		components: {
			parser
		},
		data() {
			return {
				isLoad: false,
				options: {},
				// 1微信支付；2余额支付；3支付宝支付
				payList: [{
					id: 2,
					icon: 'iconqianbao c-balance',
					title: '账户余额',
					is_disabled: false
				}],
				payInd: 0,
				send_info: {
					time_index: 0,
					time: {}
				},
				orderInfo: {
					coupon_id: 0,
					address_info: {
						id: 0
					},
					member_status: 0,
					is_remember: 0,
					balance_discount_data: {
						is_balancediscount: 0,
						balance_discount_list: []
					}
				},
				lockTap: false,
				isBus: 0,
			}
		},
		computed: mapState({
			configInfo: state => state.config.configInfo,
			mineInfo: state => state.user.mineInfo,
			bellOrderParams: state => state.order.bellOrderParams,
		}),
		async onLoad() {
			await this.initIndex()
		},
		methods: {
			...mapActions(['getConfigInfo', 'getMineInfo']),
			...mapMutations(['updateUserItem', 'updateOrderItem']),
			async initIndex(refresh = false) {
				await this.getConfigInfo()
				let {
					member_status = 0,
						is_remember = 0,
						balance_discount_data = {},
				} = this.orderInfo
				let param = this.$util.deepCopy(this.bellOrderParams)
				let {
					order_type = 1
				} = param
				delete param.order_type

				if (refresh) {
					if (member_status) {
						param.is_remember = is_remember || 0
					}
					let {
						id: pay_model
					} = this.payList[this.payInd]
					param.pay_model = pay_model
					let {
						is_balancediscount,
						balance_discount_list = []
					} = balance_discount_data
					if (pay_model == 4 && is_balancediscount) {
						param.balance_discount_card_arr = this.$util.getItems(balance_discount_list)
					}
				}

				let methodModel = order_type == 1 ? 'upOrderInfo' : 'payOrderInfo'
				try {
					let data = await this.$api.order[methodModel](param)
					data.is_remember = data.is_remember * 1 || 0
					this.$util.setNavigationBarColor({
						bg: this.primaryColor
					})

					let {
						balance_discount_data: order_discount_info = {
							auth: false,
							status: 0,
							user_status: 0
						},
						recharge_status = 0,
						balance_discount_status = 0
					} = data


					let {
						alipay_status = 0,
							app_wechat_pay = 0
					} = this.configInfo
					let weixinInd = this.payList.findIndex(item => {
						return item.id == 1
					})
					if (app_wechat_pay && weixinInd == -1) {
						this.payList.unshift({
							id: 1,
							icon: 'iconweixinzhifu1 c-wechat',
							title: '微信支付'
						})
					}
					// #ifndef MP-WEIXIN 
					let alipayInd = this.payList.findIndex(item => {
						return item.id == 3
					})
					if (alipay_status && alipayInd == -1) {
						this.payList.splice(this.payList.length - 1, 0, {
							id: 3,
							icon: 'icon-alipay c-alipay',
							title: '支付宝支付'
						})
					}
					// #endif


					if (!recharge_status && order_type != 1) {
						let rechargeInd = this.payList.findIndex(item => {
							return item.id == 2
						})
						if (rechargeInd != -1) {
							this.payList.splice(rechargeInd, 1)
						}
					}



					let {
						auth: balancediscount = false,
						status: discount_status = 0,
						user_status = 0,
						is_balancediscount = 0
					} = order_discount_info

					if (order_type != 1) {
						balancediscount = balancediscount && balance_discount_status
					}

					if (balancediscount || (order_type == 1 && data.pay_model == 4)) {
						let cardInd = this.payList.findIndex(item => {
							return item.id == 4
						})
						if (cardInd == -1 && (discount_status || user_status || (order_type == 1 && data.pay_model ==
								4))) {
							this.payList.unshift({
								id: 4,
								icon: 'iconcard c-discountcard',
								title: `折扣卡支付`
							})
						}
					}

					if (!refresh) {
						let pay_id = order_type == 1 ? data.pay_model : balancediscount && is_balancediscount ? 4 : 1
						this.payInd = this.payList.findIndex(item => {
							return item.id == pay_id
						})
					}

					this.orderInfo = data
					this.isLoad = true
				} catch (e) {
					this.$util.back()
					setTimeout(() => {
						this.$util.goUrl({
							url: 1,
							openType: `navigateBack`
						})
					}, 1500)
				}
				// #ifdef H5
				if (!refresh) {
					this.$jweixin.hideOptionMenu()
				}
				// #endif
			},
			async initRefresh() {
				await this.initIndex(true)
			},
			linkpress(res) {
				// #ifdef APP-PLUS
				this.$util.goUrl({
					url: res.href,
					openType: 'web'
				})
				// #endif
			},
			// 选择支付方式
			async toChangeItem(index, key = 1) {
				let {
					order_type = 1
				} = this.bellOrderParams
				if (order_type == 1) return
				let {
					id
				} = this.payList[index]
				let {
					user_cash = 0,
						pay_price,
						balance_discount_data = {
							user_status: 0
						}
				} = this.orderInfo
				let {
					status = 0,
						user_status = 0,
						is_balancediscount = 0
				} = balance_discount_data
				if (id == 2 && user_cash * 1 < pay_price * 1) {
					this.$util.showToast({
						title: `账户余额不足`
					})
					return
				}
				if (id == 4 && !user_status && status) {
					this.$util.showToast({
						title: `当前无可用卡/卡余额不足`
					})
					return
				}
				this.payInd = index
				if (id == 4 || (id !== 4 && is_balancediscount)) {
					this.orderInfo.coupon_id = 0
					this.orderInfo.is_remember = 0
					this.initRefresh()
				}
			},
			async toCheckBalanceDiscount() {
				let {
					balance_discount_data = {}
				} = this.orderInfo
				let {
					is_balancediscount: old_discount = 0,
				} = balance_discount_data
				await this.initRefresh()
				let {
					balance_discount_data: new_data = {}
				} = this.orderInfo
				let {
					is_balancediscount = 0,
				} = new_data
				if (old_discount && !is_balancediscount) {
					await this.initRefresh()
				}
			},
			toUseDiscountCard() {
				this.orderInfo.coupon_id = 0
				this.orderInfo.is_remember = 1
				let {
					id
				} = this.payList[this.payInd]
				if (id == 4) {
					this.payInd = this.payList.findIndex(item => {
						return item.id == 1
					})
				}
				this.initRefresh()
			},
			// 加/减数量
			async changeNum(mol, index) {
				let {
					id,
					service_id,
					member_info
				} = this.orderInfo.order_goods[index]
				let {
					can_buy,
					title
				} = member_info
				if (!can_buy && mol > 0) {
					let msg = title ? title.includes('会员') ? title : `${title}会员` : '会员'
					this.$util.showToast({
						title: `您还不是${msg}`
					})
					return
				}
				let {
					coach_id,
					order_id
				} = this.bellOrderParams
				if (this.lockTap) return;
				this.lockTap = true;
				let methodModel = mol > 0 ? 'addCar' : 'delCar'
				let param = mol > 0 ? {
					service_id,
					coach_id,
					order_id,
					num: 1
				} : {
					id,
					num: 1
				}
				try {
					let changeNum = await this.$api.order[methodModel](param)
					await this.toCheckBalanceDiscount()
					this.lockTap = false
				} catch (e) {
					this.lockTap = false
				}
			},
			async toPay() {
				let param = this.$util.deepCopy(this.bellOrderParams)
				let {
					order_type = 1
				} = param
				let {
					payList,
					payInd,
				} = this
				let {
					id: pay_model
				} = payList[payInd]
				let {
					user_cash = 0,
						pay_price = 0,
						is_remember = 0,
						balance_discount_data = {}
				} = this.orderInfo
				if (pay_model == 2 && user_cash * 1 < pay_price * 1) {
					this.$util.showToast({
						title: `账户余额不足`
					})
					return
				}
				let {
					is_balancediscount,
					balance_discount_list = []
				} = balance_discount_data
				let balance_discount_card_arr = ``
				if (pay_model == 4 && is_balancediscount) {
					balance_discount_card_arr = this.$util.getItems(balance_discount_list)
				}
				if (pay_model == 4 && !is_balancediscount) {
					this.$util.showToast({
						title: `请选择储值折扣卡`
					})
					return
				}

				delete param.order_type
				param = Object.assign({}, param, {
					pay_model,
					is_remember: is_remember || 0,
					balance_discount_card_arr
				})
				let methodModel = order_type == 1 ? 'upOrderGoods' : 'payOrder'

				if (this.lockTap) return
				this.lockTap = true
				this.$util.showLoading()
				try {
					let {
						pay_list,
						order_id
					} = await this.$api.order[methodModel](param)
					this.$util.hideAll
					// 微信/支付宝支付
					if (pay_list) {

						if (pay_model == 3) {
							pay_list = {
								orderInfo: pay_list,
								provider: 'alipay'
							}
						}

						// #ifdef H5
						if (pay_model == 3) {
							let {
								autograph
							} = this
							let alipay_params = `?autograph=${autograph}&id=${order_id}`
							let is_update = order_type == 1 ? 1 : 0
							if (is_update) {
								alipay_params += `&aliptype=1`
							}
							pay_list = Object.assign({}, pay_list, {
								order_id,
								page_url: 1,
								alipay_params
							})
							this.updateOrderItem({
								key: 'alipayOrderParams',
								val: pay_list
							})
							this.updateOrderItem({
								key: 'haveOperItem',
								val: true
							})
							this.$util.goUrl({
								url: `/user/pages/alipay-result${alipay_params}`,
								openType: `redirectTo`
							})
							return
						}
						// #endif

						try {
							await this.$util.pay(pay_list)
							this.$util.showToast({
								title: `支付成功`
							})
							setTimeout(() => {
								this.lockTap = false
								this.$util.back()
								this.$util.goUrl({
									url: 1,
									openType: `navigateBack`
								})
								// this.$util.goUrl({
								// 	url: '/pages/order?tab=3',
								// 	openType: `reLaunch`
								// })
							}, 1000)
						} catch (e) {
							this.$util.showToast({
								title: `支付失败`
							})
							setTimeout(() => {
								this.lockTap = false
								this.$util.back()
								this.$util.goUrl({
									url: 1,
									openType: `navigateBack`
								})
							}, 1000)
						}
						return
					}
					// 余额支付/零元支付
					this.$util.showToast({
						title: `支付成功`
					})
					setTimeout(() => {
						this.lockTap = false
						this.$util.back()
						this.$util.goUrl({
							url: 1,
							openType: `navigateBack`
						})
					}, 1000)
				} catch (e) {
					setTimeout(() => {
						this.lockTap = false
						this.$util.hideAll()
					}, 2000)
				}
			}
		}
	}
</script>


<style lang="scss">
	.order-pages {
		.list-item {
			.item-img {
				width: 140rpx;
				height: 140rpx;
			}

			.item-tag {
				width: 100rpx;
				height: 36rpx;
				margin-top: -18rpx;
			}

			.iconyduixingxingshixin {
				font-size: 28rpx;
			}

			.item-btn {
				width: 129rpx;
				height: 54rpx;
			}
		}

		.pay-info {
			height: 110rpx;
			bottom: 0;
			height: calc(110rpx + env(safe-area-inset-bottom) / 2);
			padding-bottom: calc(env(safe-area-inset-bottom) / 2);

			.pay-btn {
				width: 182rpx;
				height: 74rpx;
			}
		}

		.popup-rule {
			width: 680rpx;
			height: auto;

			.rule-text {
				min-height: 300rpx;
				max-height: 60vh;
			}

			.iconfont {
				font-size: 60rpx;
			}
		}
	}
</style>